<template>
  <Container class="card-edit">
    <div class="container-header title title-center" slot="header">{{id ? '编辑服务' : '新增服务'}}
      <Button
        size="large"
        class="fl btn-back"
        icon="ios-arrow-back"
        @click="$router.back()"
      >返回</Button>
    </div>
    <div class="bg-light mt pt pb">
      <Form :model="form" :rules="rules" :label-width="100" ref="form">
        <template v-if="id">
          <FormItem label="服务分类" class="wp40">
            <span>{{form.categoryName}}</span>
          </FormItem>
        </template>
        <template v-else>
          <FormItem label="服务类型" prop="categoryId" class="wp40">
            <Select v-model="form.categoryId" clearable>
              <Option
                v-for="item in allType"
                :value="item.categoryId"
                :key="item.categoryId">{{item.name}}</Option>
            </Select>
          </FormItem>
        </template>
        <!-- <FormItem label="服务类型" prop="categoryId" class="wp40">
          <Select v-model="form.categoryId" clearable>
            <Option
              v-for="item in allType"
              :value="item.categoryId"
              :key="item.categoryId">{{item.name}}</Option>
          </Select>
        </FormItem> -->
        <!-- <FormItem label="服务编码" prop="sn" class="wp40">
          <Input v-model="form.sn" placeholder="请输入服务编码" :maxlength="30"/>
        </FormItem> -->
        <FormItem label="服务名称" prop="name" class="wp40">
          <Input v-model="form.name" placeholder="请输入服务名称" :maxlength="30"/>
        </FormItem>
        <FormItem label="服务单价" prop="price" class="wp40">
          <InputNumber :max="999999" :min="0" v-model="form.price" placeholder="请输入服务单价" style="width:100%"></InputNumber>
        </FormItem>
        <FormItem label="服务说明" prop="description" class="wp40">
          <Input v-model="form.description" type="textarea" :maxlength="60" :autosize="{minRows: 3}"/>
        </FormItem>
        <FormItem label="图片" prop="imgUrl">
          <Input v-model="form.imgUrl" v-show="form.isImg"/>
          <PictureEditItem :uploadList="uploadList" :maxlength="1" @uploadPic="uploadPic"></PictureEditItem>
        </FormItem>
        <FormItem label="是否启用">
          <Checkbox label="是否启用" v-model="form.isEnabled"></Checkbox>
        </FormItem>
      </Form>
    </div>
    <Loader :status="status" @refresh="getData"></Loader>
    <div class="container-footer bg-white" slot="footer">
      <Button size="large" class="fr btn-back" type="primary" @click="onSave">保存</Button>
    </div>
  </Container>
</template>
<script>
import PictureEditItem from '@/components/PictureEditItem'
export default {
  components: {
    PictureEditItem
  },
  data() {
    const validateSn = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入服务编码'))
      } else if (!(/^[0-9]+$/).test(value)) {
        callback(new Error('输入的服务编码必须为数字'))
      } else {
        callback()
      }
    }
    return {
      id: this.$route.query.id || '',
      categoryId: this.$route.query.categoryId || '',
      status: 'pass',
      uploadList: [],
      allType: [],
      form: {
        name: '',
        description: '',
        isEnabled: true,
        price: '',
        imgUrl: '',
        // sn: '',
        categoryName: '',
        categoryId: '',
        isImg: false,
        options: {
          orderStatus: [{
            value: 1,
            label: '补胎服务'
          }, {
            value: 2,
            label: '上门服务'
          }]
        }
      },
      rules: {
        categoryId: [{ message: '请选择服务类型', trigger: 'change', required: true }],
        // sn: [{ validator: validateSn, trigger: 'blur', required: true }],
        name: [{ message: '请输入服务名称', trigger: 'blur', required: true }],
        price: [{ message: '请输入服务单价', required: true, type: 'number', trigger: 'change' }],
        description: [{ message: '请输入服务说明', trigger: 'blur', required: true }],
        imgUrl: [{ message: '请上传图片', trigger: 'change', required: true }]
      }
    }
  },
  mounted() {
    if (this.id) this.getData()
    this.getType()
  },
  destroyed() {
    this.$bus.$off()
  },
  methods: {
    uploadPic(val) {
      this.form.imgUrl = val.length > 0 ? val[0].imgUrl : ''
    },
    resetForm() {
      this.$refs.form.resetFields()
      this.uploadList = []
      this.form = {
        name: '',
        description: '',
        imgUrl: '',
        price: '',
        imgUrl: '',
        // sn: '',
        categoryName: '',
        categoryId: '',
        isEnabled: false
      }
    },
    updateForm(id) {
      this.resetForm();
      if (id) this.getData(id)
    },
    getData() {
      this.status = 'loading'
      this.$ajaxGet('/server/store_server/detail/' + this.id ).then(data => {
        this.form = {
          id: data.id,
          name: data.name,
          categoryName: data.categoryName,
          categoryId: data.categoryId,
          description: data.description,
          isEnabled: data.isEnabled,
          price: data.price,
          imgUrl: data.imgUrl,
          // sn: data.sn
        }
        this.uploadList = data.imgUrl ? [{
          imgUrl: data.imgUrl,
          status: 'finished'
        }] : []
        this.status = 'pass'
      }).catch(()=> {
        this.status = 'error'
      })
    },
    getType() {
      this.$ajaxGet('/server/server_category/list_all').then(data => {
        this.allType = (data || []).map(item => {
          return {
            categoryId: item.id,
            name: item.name
          }
        })
      })
    },
    onSave() {
      if (this.status === 'loading') return
      let text = this.id ? '编辑' : '新增'
      this.$refs.form.validate(valid => {
        if(valid) {
          let url = '/server/store_server/save'
          let param = {
            description: this.form.description,
            imgUrl: this.form.imgUrl,
            name: this.form.name,
            price: this.form.price,
            categoryId: this.form.categoryId,
            isEnabled: this.form.isEnabled,
            // sn: this.form.sn
          }
          if (this.id) param.id = this.id
          this.status = 'loading'
          this.$jsonPost(url, param).then(data => {
            this.$Notice.success({
              title: text + '成功'
            })
            this.$router.push('/product/project/list')
            this.status = 'pass'
          }).catch(() => {
            this.$Notice.error({
              title: text + '失败'
            })
            this.status = 'error'
          })
        }
      })
    }
  }
}
</script>